<template>
    <view class="my-page" :style="{ height: navBarHeight + 'px', paddingTop: statusBarHeight + 'px' }">
        <!-- 顶部个人信息区域：渐变背景、头像、姓名 -->
        <view class="profile-header" v-if="userStore.isAuthenticated">
            <view class="avatar-ring">
                <image class="avatar" :src="userStore.userInfo?.avatarUrl || '/static/logo.png'" mode="aspectFill"
                    @click="selectAvatar" />
            </view>
            <text class="user-name">{{ userStore.userInfo?.nickname || '未设置昵称' }}</text>
            <view class="user-info">
                <text class="user-email">{{ userStore.userInfo?.email }}</text>
                <view class="user-badges">
                    <text class="badge premium" v-if="userStore.userInfo?.isPremium">VIP</text>
                    <text class="badge role">{{ userStore.userInfo?.role }}</text>
                </view>
            </view>
        </view>

        <!-- 未登录状态 -->
        <view class="login-header" v-else>
            <view class="login-content">
                <text class="login-title">欢迎使用</text>
                <text class="login-subtitle">请先登录以获取更好的体验</text>
                <button class="login-btn" @click="showLogin" :disabled="loginLoading">
                    <text v-if="loginLoading" class="loading-text">登录中...</text>
                    <text v-else>立即登录</text>
                </button>
            </view>
        </view>

        <!-- 快捷功能卡片：我的收藏 / 关注公众号 / 联系客服 -->
        <view class="card shortcuts-card">
            <!-- 我的收藏 -->
            <view class="shortcut" @click="onShortcut({ key: 'fav', label: '我的收藏' })">
                <view class="shortcut-icon">
                    <text class="icon-text">🔖</text>
                </view>
                <text class="shortcut-label">我的收藏</text>
            </view>

            <!-- 关注公众号 -->
            <view class="shortcut" @click="onShortcut({ key: 'mp', label: '关注公众号' })">
                <view class="shortcut-icon">
                    <text class="icon-text">👥</text>
                </view>
                <text class="shortcut-label">关注公众号</text>
            </view>

            <!-- 联系客服 -->
            <view class="shortcut">
                <view class="shortcut-icon">
                    <text class="icon-text">🎧</text>
                </view>
                <text class="shortcut-label">联系客服</text>
                <!-- 微信小程序官方组件 -->
                <button open-type="contact" class="kefu-btn">
                    联系客服
                </button>
            </view>
        </view>
        <!-- 账户信息卡片 -->
        <view class="card contact-card" v-if="userStore.isAuthenticated">
            <view class="contact-row" @click="onInfo('email')">
                <text class="contact-label">邮箱</text>
                <text class="contact-text">{{ userStore.userInfo?.email }}</text>
                <text class="chevron">›</text>
            </view>
            <view class="contact-row" @click="onInfo('createTime')">
                <text class="contact-label">注册时间</text>
                <text class="contact-text">{{ formatDate(userStore.userInfo?.createTime || '') }}</text>
                <text class="chevron">›</text>
            </view>
            <view class="contact-row logout-row" @click="handleLogout">
                <text class="contact-label logout-text">退出登录</text>
                <text class="chevron">›</text>
            </view>
        </view>

    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useNavBar } from '@/hooks/useNavBar'
import { useUserStore } from '@/stores/user'

const { statusBarHeight, navBarHeight } = useNavBar()
const userStore = useUserStore()
function selectAvatar() {
    uni.navigateTo({
        url: '/pages/login/login'
    })
}

// 加载状态
const loading = ref(false)
const loginLoading = ref(false)

// 快捷功能配置（简单直观）
const shortcuts = ref([
    { key: 'fav', label: '我的收藏', icon: '🔖' },
    { key: 'mp', label: '关注公众号', icon: '👥' },
    { key: 'cs', label: '联系客服', icon: '🎧' }
])

/**
 * 显示登录弹窗
 */
const showLogin = async () => {
    if (loginLoading.value) return

    loginLoading.value = true
    try {
        // 先获取微信登录code
        const { code } = await uni.login({
            provider: 'weixin'
        })

        // 检查用户是否已注册
        const result = await userStore.checkUserRegistration(code)

        if (result.isRegistered && result.user) {
            // 用户已注册，直接设置用户信息并登录
            userStore.setToken(result.user.token || '')
            userStore.setUserInfo(result.user)

            uni.showToast({
                title: '登录成功',
                icon: 'success'
            })

            // 重新获取用户信息以确保数据最新
            await userStore.fetchUserProfile()
        } else {
            // 用户未注册，显示登录弹窗
            uni.navigateTo({
                url: '/pages/login/login'
            })
        }
    } catch (error) {
        console.error('检查用户状态失败:', error)
        // 如果检查失败，显示登录弹窗
        uni.navigateTo({
            url: '/pages/login/login'
        })
    } finally {
        loginLoading.value = false
    }
}

/**
 * 处理退出登录
 */
const handleLogout = () => {
    uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
            if (res.confirm) {
                userStore.logout()
                uni.showToast({
                    title: '已退出登录',
                    icon: 'success'
                })
            }
        }
    })
}

/**
 * 检查登录状态
 */
const checkLoginStatus = async () => {
    loading.value = true
    try {
        const isLoggedIn = await userStore.checkLoginStatus()
        if (!isLoggedIn) {
            // 如果未登录，可以选择是否自动弹出登录框
            // showLogin()
        }
    } catch (error) {
        console.error('检查登录状态失败:', error)
    } finally {
        loading.value = false
    }
}

/**
 * 获取登录方式文本
 */
const getLoginTypeText = (loginType: string) => {
    const typeMap: Record<string, string> = {
        email: '邮箱登录',
        phone: '手机登录',
        wechat: '微信登录',
        qq: 'QQ登录'
    }
    return typeMap[loginType] || loginType
}

/**
 * 格式化日期
 */
const formatDate = (dateStr: string) => {
    if (!dateStr) return '未知'
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

/**
 * 打开公众号关注页面
 */
const openOfficialAccount = () => {
    // #ifdef MP-WEIXIN
    // @ts-ignore
    wx.openOfficialAccountProfile({
        username: 'gh_bf43b008599d', // 请替换为您的公众号AppID
        success: (res: any) => {
            console.log('打开公众号成功', res)
        },
        fail: (err: any) => {
            console.error('打开公众号失败', err)
            uni.showToast({
                title: '打开公众号失败',
                icon: 'none'
            })
        }
    })
    // #endif

    // #ifndef MP-WEIXIN
    uni.showToast({
        title: '请在微信小程序中使用',
        icon: 'none'
    })
    // #endif
}

// 事件：快捷功能点击
const onShortcut = (s: { key: string; label: string }) => {
    switch (s.key) {
        case 'fav':
            // 我的收藏 - 检查登录状态
            if (!userStore.isAuthenticated) {
                uni.navigateTo({
                    url: '/pages/login/login'
                })
                return
            }
            // 已登录，跳转到收藏页面
            uni.navigateTo({
                url: '/pages/favorites/favorites'
            })
            break
        case 'mp':
            // 关注公众号 - 使用微信官方API
            openOfficialAccount()
            break
        default:
            uni.showToast({ title: s.label, icon: 'none' })
    }
}

// 事件：信息点击
const onInfo = (type: string) => {
    uni.showToast({ title: `点击了${type}`, icon: 'none' })
}




// 监听登录成功事件
const handleLoginSuccess = () => {
    console.log('收到登录成功事件，刷新页面数据')
    checkLoginStatus()
}

// 页面加载时检查登录状态
onMounted(() => {
    checkLoginStatus()
    // 监听登录成功事件
    uni.$on('loginSuccess', handleLoginSuccess)
})

// 页面卸载时移除事件监听
onUnmounted(() => {
    uni.$off('loginSuccess', handleLoginSuccess)
})
</script>

<style lang="scss" scoped>
.my-page {
    min-height: 100vh;
    background: #eef2f7;
}

/* 未登录状态样式 */
.login-header {
    height: 180px;
    padding-top: 80px;
    padding-bottom: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #c6e1ff 0%, #e8d6ff 50%, #c8f5e3 100%);
}

.login-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;
}

.login-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #111827;
}

.login-subtitle {
    font-size: 28rpx;
    color: #6b7280;
    margin-bottom: 8rpx;
}

.login-btn {
    padding: 1px 48px;
    background: linear-gradient(90deg, #7f66f0, #a855f7);
    color: #fff;
    border-radius: 50rpx;
    font-size: 28rpx;
    font-weight: 500;
    border: none;
    box-shadow: 0 4rpx 12rpx rgba(127, 102, 240, 0.3);
    transition: all 0.3s ease;

    &::after {
        border: none;
    }

    &:active {
        opacity: 0.9;
    }

    &:disabled {
        opacity: 0.6;
        background: #9ca3af;
        box-shadow: none;
    }

    .loading-text {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8rpx;

        &::before {
            content: '';
            width: 20rpx;
            height: 20rpx;
            border: 2rpx solid #fff;
            border-top: 2rpx solid transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
    }
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 顶部信息区：柔和多彩渐变 + 圆形头像 */
.profile-header {
    height: 180px;
    padding-top: 180px;
    /* 增加底部内边距，为悬浮卡片预留空间 */
    padding-bottom: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: linear-gradient(135deg, #c6e1ff 0%, #e8d6ff 50%, #c8f5e3 100%);
}

.avatar-ring {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    padding: 6rpx;
    /* 白色描边 */
    background: #fff;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
}

.avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
}

.user-name {
    margin-top: 16rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #111827;
}

.user-info {
    margin-top: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
}

.user-email {
    font-size: 24rpx;
    color: #6b7280;
}

.user-badges {
    display: flex;
    gap: 12rpx;
}

.badge {
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    font-size: 20rpx;
    font-weight: 500;
}

.badge.premium {
    background-color: #fef3c7;
    color: #d97706;
}

.badge.role {
    background-color: #dbeafe;
    color: #2563eb;
}

/* 通用卡片容器 */
.card {
    background: #fff;
    border-radius: 16rpx;
    margin: 24rpx;
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.04);
}

/* 快捷功能卡片：三等分布局 */
.shortcuts-card {
    padding: 24rpx 20rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    /* 设置为悬浮效果：上移并提高层级 */
    margin: 0 24rpx;
    margin-top: -50px;
    position: relative;
    z-index: 10;
}

.shortcut {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

/* 图标容器：蓝色清爽渐变圆角方块 */
.shortcut-icon {
    width: 90rpx;
    height: 90rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #a8dbff 0%, #bfe6ff 100%);
}

.icon-text {
    font-size: 42rpx;
}

.shortcut-label {
    margin-top: 12rpx;
    font-size: 24rpx;
    color: #4b5563;
}

/* 客服按钮样式 */
.kefu-btn {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
    border: none;
    padding: 0;
    margin: 0;
    font-size: 0;
    opacity: 0;

    &::after {
        border: none;
    }
}

/* 联系方式卡片：两行信息，右侧箭头 */
.contact-card {
    padding: 0 24rpx;
    /* 由于上方卡片悬浮，上移了 40rpx，这里适当增加顶部间距 */
    margin-top: 48rpx;
}

.contact-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 28rpx 0;
    border-bottom: 1rpx solid #f1f5f9;
}

.contact-row:last-child {
    border-bottom: none;
}

.logout-row {
    .logout-text {
        color: #ef4444;
    }
}

.contact-label {
    font-size: 28rpx;
    color: #6b7280;
    min-width: 120rpx;
}

.contact-text {
    font-size: 28rpx;
    color: #1f2937;
    flex: 1;
    text-align: right;
    margin-right: 16rpx;
}

.chevron {
    font-size: 32rpx;
    color: #9ca3af;
}
</style>